package org.micode.libs.servlet.interceptor;

import org.micode.common.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public class BaseInterceptor extends AbstractInterceptor {

    /**
     * 返回结果
     *
     * @param response
     * @param result
     */
    protected void returnResult(HttpServletResponse response, Object result) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(JsonUtils.toJson(result));
        } catch (IOException e) {
            log.error("response error", e);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    @Override
    protected void beginPreHandle(HttpServletRequest httpServletRequest) {

    }

    @Override
    protected boolean checkPermission(HttpServletRequest httpServletRequest,
                                      HttpServletResponse httpServletResponse,
                                      Object handler) throws IOException {
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {
        log.trace("Into postHandle()");
    }

    @Override
    protected void endAfterCompletion() {

    }

    @Override
    protected void afterHandle(HttpServletRequest httpServletRequest,
                               HttpServletResponse httpServletResponse,
                               Object o, Exception e) {

    }
}
